package com.tencent.wxcloudrun.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.tencent.wxcloudrun.model.Categories;
import com.tencent.wxcloudrun.model.Comment;
import com.tencent.wxcloudrun.model.Post;
import com.tencent.wxcloudrun.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;


import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

/**
 * @author lichongbing
 * @version 1.0.0
 * @createdate 2023/2/16 19:47
 * @description: TODO
 */
@RestController
public class CommentController {
    @Autowired
    private CommentService commentService;

    @Autowired
    private UploadService uploadService;

    @Autowired
    private RestTemplate restTemplate;


    @Autowired
    private UserService userService;


    @Autowired
    private CategoriesService categoriesService;


    @PostMapping(value = "comment/add")
    JSONObject addComment(@RequestBody JSONObject jsonObject, HttpServletRequest requests) {
        String openid = requests.getHeader("X-WX-OPENID");
        String author_name = jsonObject.getString("author_name");
        String author_url = jsonObject.getString("author_url");
        String content = jsonObject.getString("content");
        String parent = jsonObject.getString("parent");
        String post = jsonObject.getString("post");
        String userid = jsonObject.getString("userid");
        Comment comment = new Comment();
        comment.setContent(content);
        comment.setAuthor_name(author_name);
        comment.setAuthor_url(author_url);
        comment.setParent_id(Integer.valueOf(parent));
        comment.setPost_id(post);
        comment.setUserid(userid);
        comment.setOpenid(openid);
        int i = commentService.addComent(comment);
        JSONObject jsonObject1 = new JSONObject();
        if (i > 0) {
            jsonObject1.put("code", "success");
            jsonObject1.put("message", "评论添加成功");
            return jsonObject1;
        } else {
            jsonObject1.put("code", "400");
            jsonObject1.put("message", "评论添加不成功");
            return jsonObject1;
        }


    }

    /**
     * 获取文章评论
     * @param request
     * @return
     */
    @GetMapping(value = "comment/getcomments")
    JSONObject getcomments(HttpServletRequest request) {
        int postid = Integer.parseInt(request.getParameter("postid"));
        int limit = Integer.parseInt(request.getParameter("limit"));
        int page = Integer.parseInt(request.getParameter("page"));
        List<Comment> comments = commentService.getcomment(page, limit, postid);
        List<Comment> buildTree3 = test1(comments);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code", "success");
        jsonObject.put("message", "获取评论成功");
        jsonObject.put("status", "200");
        jsonObject.put("data", buildTree3);
        return jsonObject;


    }

    public static List<Comment> test1(List<Comment> platformList ){
        System.out.println(platformList.size());
        List<Comment> result = new ArrayList();
        for (Comment platform : platformList) {

            //获取根节点
            if(platform.getParent_id().equals(0)){
                result.add(platform);
            }

            for(Comment child : platformList){
                System.out.println(child.getParent_id().equals(platform.getId()));
                if(child.getParent_id().equals(platform.getId())){
                    platform.addChild(child);
                }
            }
        }

       return result;
    }


    /**
     * 我的评论
     * @param request
     * @return
     */
    @GetMapping(value = "comment/get")
    List<Post> getMyComments(HttpServletRequest request) {
        String openid = request.getHeader("X-WX-OPENID");
        // String openid = "oiRnJ5W-SUy6aFEFgR_xNSchKJYw";
        List<Post> comments = commentService.getcommentByOpenid(openid);
        for (int i = 0; i < comments.size(); i++) {
            comments.get(i).setTitle(JSON.parseObject(comments.get(i).getTitleJson()));
        }

        return comments;
    }

    @GetMapping(value = "post/mylike")
    List<Post> postmylike(HttpServletRequest request) {
        String openid = request.getHeader("X-WX-OPENID");
        //String openid = "oiRnJ5W-SUy6aFEFgR_xNSchKJYw";
        List<Post> comments = commentService.getpostmylikeByOpenid(openid);
        for (int i = 0; i < comments.size(); i++) {
            comments.get(i).setTitle(JSON.parseObject(comments.get(i).getTitleJson()));
        }

        return comments;
    }

    @PostMapping(value = "post/address")
    String address(HttpServletRequest request,@RequestBody JSONObject jsonObject) {
        String openid = request.getHeader("X-WX-OPENID");
        String address = jsonObject.getString("address");
        String town = jsonObject.getString("town");
        String province = jsonObject.getString("province");
        String city = jsonObject.getString("city");
        String district = jsonObject.getString("district");
        int id = Integer.parseInt(jsonObject.getString("id"));
        int comments = commentService.updateaddressbyopenid(openid,address,town,id);
        Categories categories = new Categories();
        categories.setId(id);
        categories.setCount(0);
        categories.setDescription(province+city+district+town+"本地生活信息");
        categories.setName(town);
        Categories categories1 = categoriesService.getCategory(id);
        if (categories1 == null){
            int add = categoriesService.addCategory(categories);
        }
        return address;
    }
    /**
     * {crossroad={id=5717722, title=通川北路/健民路(路口), location={lat=31.21942, lng=107.51041}, _distance=202.7, _dir_desc=西}, town={id=511702001, title=东城街道, location={lat=31.212699, lng=107.507925}, _distance=0, _dir_desc=内}, street_number={id=46476490832070645740, title=北翎路64号, location={lat=31.22023, lng=107.50857}, _distance=45.4, _dir_desc=西南}, street={id=3402321994365568861, title=北翎路, location={lat=31.220583, lng=107.507607}, _distance=25.1, _dir_desc=南}, landmark_l2={id=2550208792746036078, title=达州市土地储备中心, location={lat=31.219584, lng=107.508733}, _distance=54.5, _dir_desc=西北}}
     */



    /**
     * 专题订阅
     * @param request
     * @return
     */
    @GetMapping(value = "category/getsubscription")
    JSONObject getsubscription(HttpServletRequest request) {
        String openid = request.getHeader("X-WX-OPENID");
        return null;
    }


    @GetMapping(value = "category/ids")
    JSONObject ids(HttpServletRequest request) {
        String openid = request.getHeader("X-WX-OPENID");
        return null;
    }



    @PostMapping(value = "/weixin/qrcodeimg")
    JSONObject qrcodeimg(@RequestBody JSONObject jsonObject,HttpServletRequest request) throws Exception {
//        String header = request.getHeader("x-openapi-seqi");
//        String tokenurl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wx9912c43ed2e85163&secret=f0bf2f9c37edeceb06bc7af5be76c8cf";
//        HttpHeaders headers0 = new HttpHeaders();
//        headers0.setContentType(MediaType.APPLICATION_JSON);
//        String pathStr0 = "";
//        HttpEntity requestEntity0 = new HttpEntity(pathStr0, headers0);
//        ResponseEntity<JSONObject> entity0 = restTemplate.exchange(tokenurl, HttpMethod.POST, requestEntity0, JSONObject.class, new Object[0]);
//        JSONObject body = entity0.getBody();
//        String access_token = body.getString("access_token");

        //System.out.println(access_token);
        String path = jsonObject.getString("path");
        //String path = "pages/detail/detail?id=2434";
        String postid = jsonObject.getString("postid");

        JSONObject pathjson = new JSONObject();
        pathjson.put("path", path);
        String pathStr = pathjson.toString();
        String url = "https://api.weixin.qq.com/wxa/getwxacode?";
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        HttpEntity requestEntity = new HttpEntity(pathStr, headers);
        ResponseEntity<byte[]> entity = restTemplate.exchange(url, HttpMethod.POST, requestEntity, byte[].class, new Object[0]);
        byte[] result = entity.getBody();
        String  originalFilename  = "qrcode-"+postid+".png";
        String basePath = "";
        JSONObject res = new JSONObject();
        res.put("code","success");
        String qrcodeimgUrl = uploadService.writeToStore(result, basePath, originalFilename);
        res.put("qrcodeimgUrl",qrcodeimgUrl);
        return res;
    }
    @PostMapping(value = "/qrcodeimg")
    JSONObject upqrcodeimg(MultipartHttpServletRequest request) throws Exception {
        String openid = request.getParameter("openid");
        String basePath = "";
        MultipartFile file = request.getFile("file");
        byte[] bytes = file.getBytes();
        String originalFilename = file.getOriginalFilename();
        String path = uploadService.storeScale(file, basePath, 132,132);
        JSONObject jsonObject = new JSONObject();
        int i = userService.updateAvatarUrl(path, openid);
        if(i>0){
            jsonObject.put("success",true);
            jsonObject.put("avatarUrl",path);
            jsonObject.put("enableUpdateAvatarCount", 2);
            jsonObject.put("message", "头像更新成功");
        }else {
            jsonObject.put("success", false);
            jsonObject.put("message", "头像更新不成功");
        }
        return jsonObject;
    }





}
